<template>
  <div class="more-rank-container">
    <div class="header">
      <button
          class="back-button"
          @click="goBack"
      >
        <span class="back-icon">←</span>
        <span>返回榜单</span>
      </button>
      <h1 class="title">{{ tabLabel }}更多电影</h1>
    </div>

    <el-row :gutter="20" class="movie-list">
      <el-col :span="6" v-for="movie in movies" :key="movie.id">
        <el-card class="movie-card" shadow="hover" @click="goToMovieDetail(movie.id)">
          <img
              :src="movie.poster || movie.coverUrl || placeholderImg"
              alt="电影海报"
              class="movie-poster"
          />
          <div class="movie-info">
            <p class="movie-title" :title="movie.title">{{ movie.title }}</p>
            <p class="movie-score" v-if="movie.finalScore || movie.avgScore">
              评分: {{ movie.finalScore || movie.avgScore }}
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="pagination-container" v-if="movies.length">
      <el-button
          :disabled="page === 1"
          icon="el-icon-arrow-left"
          @click="prevPage"
          class="page-btn"
      >
        上一页

      </el-button>

      <span class="page-info">第 {{ page }} / {{ totalPages }} 页</span>

      <el-button
          :disabled="!hasMore"
          icon="el-icon-arrow-right"
          @click="nextPage"
          class="page-btn"
      >
        下一页
      </el-button>
    </div>


    <div v-if="loading" class="loading-text">加载中...</div>
    <div v-if="error" class="error-text">{{ error }}</div>
    <div v-if="!loading && movies.length === 0" class="empty-text">暂无电影数据</div>
  </div>
</template>

<script>
import {getMoreMoviesByRank} from '@/api/movie/movie.js'

export default {
  name: 'MoreRank',
  data() {
    return {
      movies: [],
      page: 1,
      size: 8,

      totalCount: 0,
      loading: false,
      error: '',
      hasMore: true,
      tabLabel: '',
      placeholderImg: 'https://via.placeholder.com/100x140?text=No+Image',
    }
  },
  computed: {
    totalPages() {
      // 计算总页数
      return Math.ceil(this.totalCount / this.size)
    },
    canPrev() {
      return this.page > 1
    },
    canNext() {
      return this.page < this.totalPages
    }
  },
  watch: {
    // 监听路由参数变化，重新加载数据
    '$route.params.name': {
      immediate: true,
      handler(newName) {
        this.resetData()
        this.tabLabel = this.getTabLabel(newName)
        this.fetchMovies()
      },
    },
  },
  methods: {
    async prevPage() {
      if (this.canPrev) {
        this.page--
        await this.fetchMovies()
      }
    },
    async nextPage() {
      if (this.canNext) {
        this.page++
        await this.fetchMovies()
      }
    },
    goBack() {
      // 获取从年度榜单页面传来的位置信息
      const scrollTop = this.$route.query.scrollTop || 0
      const currentUnit = this.$route.query.currentUnit || 0

      // 返回到年度榜单页面并恢复原位置
      this.$router.push({ 
        name: 'AnnualMovie', 
        query: { scrollTop, currentUnit } 
      })
    },
    goToMovieDetail(movieId) {
      // 跳转到电影详情页面
      this.$router.push({
        path: `/movie/${movieId}`,
        query: { 
          from: 'more-rank',
          rankName: this.$route.params.name
        }
      })
    },
    getTabLabel(name) {
      const map = {
        latest: '最新上映',
        highscore: '高分佳片',
        chinese: '华语佳片',
        action: '动作犯罪惊悚',
        scifi: '奇幻科幻',
        suspense: '悬疑烧脑片',
        nolan: '诺兰导演精选',
      }
      return map[name] || name
    },
    resetData() {
      this.movies = []
      this.page = 1
      this.loading = false
      this.error = ''
      this.hasMore = true
    },
    async fetchMovies() {
      if (this.loading) return
      this.loading = true
      this.error = ''
      try {
        const name = this.$route.params.name
        console.log('前端获取到的参数 - name:', name, 'route.params:', this.$route.params)
        const res = await getMoreMoviesByRank(name, this.page, this.size)
        const data = res.data.records || res.data  // 根据你接口返回格式调整
        this.totalCount = res.data.total || 0     // 总数字段，确认接口返回结构
        if (!Array.isArray(data)) {
          this.error = '接口返回数据格式错误'
          return
        }

        this.movies = data.map(movie => {
          if (movie.poster && movie.poster.startsWith('http')) {
            movie.poster = `https://images.weserv.nl/?url=${movie.poster.replace(/^https?:\/\//, '')}`
          }
          return movie
        })

        // 判断是否还有下一页
        this.hasMore = this.page < this.totalPages

      } catch (err) {
        console.error(err)
        this.error = '加载失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },
  },
}
</script>

<style scoped>




/* 分页导航样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40px;
  gap: 20px;
}

.page-info {
  font-size: 16px;
  color: #444;
  font-weight: 600;
}

.page-btn {
  border-radius: 8px;
  font-size: 18px;
  padding: 10px 16px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  background-color: #1890ff;
  color: white;
  transition: all 0.3s ease;
}

.page-btn:hover {
  background-color: #40a9ff;
  box-shadow: 0 6px 20px rgba(24, 144, 255, 0.5);
}
.page-btn:disabled {
  background-color: #dcdfe6;
  color: #aaa;
  box-shadow: none;
}

.more-rank-container {
  max-width: 1200px;
  margin: 40px auto 80px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  gap: 24px;
  flex-wrap: wrap;
  justify-content: space-between; /* 按钮靠左，标题居中 */
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  position: relative;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  min-width: 120px;  /* 确保有足够宽度 */
  white-space: nowrap; /* 防止文字换行 */
}

.back-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.back-button:active {
  transform: translateY(0);
}

.back-icon {
  font-size: 18px;
  font-weight: bold;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  white-space: nowrap;
  user-select: none;
  margin: 0;
  text-align: center;
}

.movie-list {
  flex-grow: 1;
}

.movie-card {
  border-radius: 20px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid transparent;
}

.movie-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 30px rgba(102, 126, 234, 0.3);
  border-color: rgba(102, 126, 234, 0.2);
}

.movie-poster {
  width: 100%;
  height: 220px;
  object-fit: cover;
  border-radius: 16px 16px 0 0;
}

.movie-info {
  padding: 12px 10px;
}

.movie-title {
  font-weight: 700;
  font-size: 18px;
  margin: 0 0 6px;
  color: #222;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.movie-score {
  font-size: 14px;
  color: #555;
}

/* 其他文本样式 */
.loading-text,
.error-text,
.empty-text {
  margin-top: 30px;
  font-size: 16px;
  color: #888;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .more-rank-container {
    padding: 20px;
    margin: 20px auto;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 16px;
  }
  
  .back-button {
    align-self: flex-start;
    min-width: 100px;
    padding: 10px 16px;
    font-size: 14px;
  }
  
  .title {
    position: static;
    transform: none;
    text-align: center;
    font-size: 22px;
    width: 100%;
    margin-top: 8px;
  }
  
  .movie-list {
    display: block;
  }
}
</style>
